package com.ahdms.es.engine;

import com.ahdms.es.bean.SesSignInfo;
import com.ahdms.es.result.VerifyResult;
import com.ahdms.es.util.Base64Utils;
import com.itextpdf.text.pdf.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author qinxiang
 * @date 2021-04-12 15:04
 */
public class PdfFileVerifyEngine extends FileVerifyEngine{

    private PdfReader pdfReader;

    private byte[] fileData;

    public PdfFileVerifyEngine(byte[] fileData) throws IOException {
        pdfReader = new PdfReader(fileData);
        this.fileData = fileData;
    }

    @Override
    public List<VerifyResult<SesSignInfo>> verify() {
        AcroFields fields = pdfReader.getAcroFields();
        ArrayList<String> names = fields.getSignatureNames();
        List<VerifyResult<SesSignInfo>> result = new ArrayList<>();
        for(int i=0;i<names.size();i++){
            PdfDictionary signatureDictionary = fields.getSignatureDictionary(names.get(i));
            PdfObject pdfObject = signatureDictionary.get(PdfName.CONTENTS);
            String signId = pdfObject.toString();
            // *****从byteRange中得到验签所需的原文 begin****
            String[] range = parseArray(signatureDictionary);
            byte[] original = new byte[Integer.parseInt(range[1]) + Integer.parseInt(range[3])];

            System.arraycopy(fileData, 0, original, 0, Integer.parseInt(range[1]));
            if(i == names.size()-1){
                System.arraycopy(fileData, fileData.length-Integer.parseInt(range[3]), original, Integer.parseInt(range[1]),
                        Integer.parseInt(range[3]));
            }else{
                System.arraycopy(fileData, Integer.parseInt(range[2]), original, Integer.parseInt(range[1]),
                        Integer.parseInt(range[3]));
            }
            VerifyResult<SesSignInfo> verifyResult = SesSignatureVerifyEngine.verifySesSignature(Base64Utils.decode(signId), original);
            result.add(verifyResult);
        }
        return result;
    }

    private String[] parseArray(PdfDictionary signatureDictionary){
        //ByteRange 内容为 [a, b, c, d]
        PdfArray pdfArray = signatureDictionary.getAsArray(PdfName.BYTERANGE);
        String str = pdfArray.toString();
        String strArr = str.substring(1, str.length()-1);
        String[] range = strArr.split(", ");
        return range;
    }

}
